import React from 'react';
import { Button, Table, message } from 'antd';
import { deleteImage } from 'services/image';
import timeFormat from 'utils/time';
import ConfirmDeleteButton from 'components/ConfirmDeleteButton';
import { defaultRejectHandler } from 'utils/http';
import DescriptionsModal from './modal/DescriptionsModal';
import UploadModal from './modal/UploadModal';

export default class ImageManage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visibleDescri: false,
      visibleUpload: false,
      envData: [],
      uploading: false,
    };
  }

  setUploading = (uploading) => {
    this.setState({ uploading });
  }

  updateTable = () => {
    const { updateImage } = this.props;
    this.setState({ visibleUpload: false });
    updateImage();
  }

  render() {
    const { dataSource, updateImage, loading } = this.props;
    const {
      visibleDescri, visibleUpload, envData, uploading,
    } = this.state;
    const columns = [
      {
        title: '镜像名称',
        dataIndex: 'tag',
        key: 'tag',
      },
      {
        title: '创建时间',
        dataIndex: 'created',
        key: 'created',
        render: timeFormat,
      },
      {
        title: '操作',
        key: 'action',
        render: (record) => (
          <span>
            <Button
              style={{ marginRight: '10px' }}
              size="small"
              onClick={() => {
                this.setState({
                  visibleDescri: true,
                  envData: record.envs,
                });
              }}
            >
              详情
            </Button>
            <ConfirmDeleteButton
              confirmTitle="确定删除该镜像?"
              buttonText="删除"
              onConfirm={() => {
                deleteImage({ data: { image: record.id } }).then(() => {
                  message.success('操作成功！');
                  updateImage();
                }, defaultRejectHandler);
              }}
            />
          </span>
        ),
      },
      {
        title: (
          <Button loading={uploading} type="dashed" icon="plus" onClick={() => this.setState({ visibleUpload: true })} />
        ),
        key: 'add',
        render: () => null,
      },
    ];
    return (
      <>
        <Table columns={columns} dataSource={dataSource} size="middle" rowKey="id" loading={loading} />
        <DescriptionsModal
          dataSource={envData}
          visible={visibleDescri}
          changeVisible={(e) => this.setState({ visibleDescri: e })}
        />

        <UploadModal
          setUploading={this.setUploading}
          visible={visibleUpload}
          changeVisible={(e) => this.setState({ visibleUpload: e })}
          updateTable={this.updateTable}
        />
      </>
    );
  }
}
